package com.mallcai.bigdata.ladon.config;

import com.alibaba.fastjson.JSON;
import com.mallcai.bigdata.ladon.config.props.DatasourceProperties;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import java.sql.SQLException;

/**
 * Created by oneape<oneape15@163.com>
 * Created 2019-04-19 14:02.
 * Modify:
 */
@Slf4j
@Configuration
public class DatasourceConfig implements EnvironmentAware {

    @Autowired
    private DatasourceProperties dsProps;

    private Environment env;

    @Override
    public void setEnvironment(Environment environment) {
        this.env = environment;
    }

    @Bean(name="ladonDataSource", destroyMethod = "close")
    public HikariDataSource dataSource() throws SQLException {
        log.info("++++++++++++++++++++ activeProfiles: {}", JSON.toJSONString(env.getActiveProfiles()));
        log.info("init dataSource........");
        if (StringUtils.isEmpty(dsProps.getUrl())) {
            log.warn("数据库连接池配置异常!请检查你的配置文件, 当前配置参数为:{}", JSON.toJSONString(env.getActiveProfiles()));
            throw new ApplicationContextException("Database connection pool is not configured correctly!");
        }

        HikariDataSource ds = new HikariDataSource();
        ds.setDriverClassName(dsProps.getDriverClassName());
        ds.setJdbcUrl(dsProps.getUrl());
        ds.setUsername(dsProps.getUsername());
        ds.setPassword(dsProps.getPassword());
        ds.setAutoCommit(dsProps.getAutoCommit());
        ds.setMaximumPoolSize(dsProps.getMaximumPoolSize());
        ds.setConnectionTestQuery(dsProps.getValidationQuery());

        // 进行编码设置, 否则会中文乱码
        ds.addDataSourceProperty("useUnicode", "true");
        ds.addDataSourceProperty("characterEncoding", "utf8");

        return ds;
    }

    @Bean
    public PlatformTransactionManager transactionManager() throws SQLException {
        log.info("init transactionManager....");
        return new DataSourceTransactionManager(dataSource());
    }
}
